//
//  SLInformationViewModel.m
//  StarLight
//
//  Created by Duke.wu on 16/5/17.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLInformationViewModel.h"
#import "SLNewsModel.h"
#import "SLNetWork.h"



@interface SLInformationViewModel ()

@property (nonatomic, strong) NSString *requstPath;

@property (nonatomic, strong) NSNumber *pageNum;

@end


@implementation SLInformationViewModel


- (instancetype)init{
  if (self = [super init]) {
    self.pageNum = @1;
    [self setUpObservers];
      [self setInfoMationHeadData];
  }
  return self;
}


- (void)setUpObservers{
  @weakify(self)
  [RACObserve(self, pageNum) subscribeNext:^(NSNumber *page) {
    @strongify(self)
    NSString *path = [NSString stringWithFormat:@"%@%@%@?page=%@",baseUrl,@"/news",@"/newslist",page];
    self.requstPath = path;
  }];
  
  [RACObserve(self, requstPath) subscribeNext:^(NSString *path) {
    @strongify(self)
    [SLNetWork getDataWithRequest:path complete:^(id respond, NSError *error) {
      NSMutableArray *newsList = [NSMutableArray arrayWithCapacity:1];
      if (![self.pageNum isEqualToNumber:@1]) {
        [newsList addObjectsFromArray:self.newsList];
      }
      if (!error) {
        NSMutableArray *list = [SLNewsModel mj_objectArrayWithKeyValuesArray:respond[@"newslist"]];
        [newsList addObjectsFromArray:list];
  
        if ([self.pageNum isEqualToNumber:@1]) {
          NSMutableArray *bannerList = [SLNewsBannerModel mj_objectArrayWithKeyValuesArray:respond[@"topimages"]];
          self.bannerList = bannerList;
        }
        self.newsList = newsList;
      }
    }];
  }];
}

- (void)setInfoMationHeadData{
    NSString *path = [NSString stringWithFormat:@"%@%@%@?page=%@",baseUrl,@"/news",@"/fwnews",@"1"];
    @weakify(self)
        [SLNetWork getDataWithRequest:path complete:^(id respond, NSError *error) {
            @strongify(self)
            if (!error) {
                self.topnewsList = [SLNewTopnews mj_objectArrayWithKeyValuesArray:respond[@"topnews"]];
            }
        }];
}


- (void)next{
  self.pageNum = @(self.pageNum.integerValue +1);
}

- (void)first{
  self.pageNum = @1;
}

#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  return self.newsList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  SLInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
  [cell configInfoCellWith:self.newsList[indexPath.row]];
  return cell;
}










@end
